import random

def _format_item_list_as_text(item_types: list) -> str:
    """将物品类型列表格式化为自然语言，例如 ['A', 'B', 'C'] -> 'A, B, and C'"""
    if not item_types:
        return ""
    if len(item_types) == 1:
        return item_types[0]
    if len(item_types) == 2:
        return f"{item_types[0]} and {item_types[1]}"
    return f"{', '.join(item_types[:-1])}, and {item_types[-1]}"

def _create_caption_for_single_item(item_data: dict) -> str:
    """为单个物品生成描述（这是之前策略3的单物品版本）"""
    templates = [
        "A photo of a {primary_color} {item_type}. It has {details_str} and a {pattern_type} pattern. The graphic shows {graphic_desc}. It has a {style_str} style.",
        "{title}. This {item_type} is {primary_color} and features {details_str}. The design includes a graphic of {graphic_desc}. Suitable for a {style_str} look.",
        "An image of a {item_type}. Color: {primary_color}. Design details: {details_str}. Graphic: {graphic_desc}. Style: {style_str}."
    ]
    
    details_str = ', '.join(item_data.get('design_details', []))
    style_str = ', '.join(item_data.get('style_tags', []))
    
    fillings = {
        'title': item_data.get('product_title', ''),
        'item_type': item_data.get('item_type', 'item'),
        'primary_color': item_data.get('primary_color', ''),
        'details_str': details_str if details_str else 'no special details',
        'pattern_type': item_data.get('pattern_type', 'solid'),
        'graphic_desc': item_data.get('graphic_description', 'no graphic').replace('Features a ', ''),
        'style_str': style_str if style_str else 'general'
    }

    chosen_template = random.choice(templates)
    return chosen_template.format(**fillings)


def create_caption_from_json_list(item_list: list) -> str:
    """
    主函数：根据物品字典列表生成一个连贯的、随机化的文本描述。
    能自动处理单个物品或多个物品（套装）的情况。
    """
    if not isinstance(item_list, list) or not item_list:
        return "" # 如果输入为空或不是列表，返回空字符串

    # 如果列表只有一个物品，使用单物品的描述逻辑
    if len(item_list) == 1:
        return _create_caption_for_single_item(item_list[0])

    # --- 处理多个物品（套装）的逻辑 ---
    
    # 1. 提取共享信息 (以第一个物品为基准)
    base_item = item_list[0]
    primary_color = base_item.get('primary_color', 'multicolor')
    graphic_desc = base_item.get('graphic_description', 'a pattern').lower()
    style_tags = base_item.get('style_tags', [])
    style_str = _format_item_list_as_text(style_tags) if style_tags else 'a versatile'

    # 2. 提取并组合每个物品的独特信息
    item_types = [item.get('item_type', 'piece').lower() for item in item_list]
    set_composition_str = _format_item_list_as_text(item_types)

    individual_details_list = []
    for item in item_list:
        item_type = item.get('item_type', 'piece').lower()
        details = item.get('design_details', [])
        if details:
            details_str = _format_item_list_as_text(details).lower()
            individual_details_list.append(f"the {item_type} has a {details_str} design")

    individual_details_str = "; ".join(individual_details_list)

    # 3. 使用为“套装”设计的随机化模板
    templates = [
        "A photo of a matching {style_str} clothing set. The set is {primary_color} and features {graphic_desc}. It includes {set_composition_str}. Specifically, {individual_details_str}.",
        "An image of a coordinated outfit with a {primary_color}, {graphic_desc}. This {style_str} set consists of {set_composition_str}. Design highlights include: {individual_details_str}.",
        "This is a multi-piece outfit in a {style_str} style, featuring a vibrant {graphic_desc}. The set includes {set_composition_str}. {individual_details_str}.",
        "A {primary_color} clothing set with a matching abstract print. It's a complete look with {set_composition_str}. The pieces have distinct features: {individual_details_str}."
    ]

    fillings = {
        'style_str': style_str,
        'primary_color': primary_color,
        'graphic_desc': graphic_desc,
        'set_composition_str': set_composition_str,
        'individual_details_str': individual_details_str if individual_details_str else "The pieces are designed to match perfectly",
    }
    
    chosen_template = random.choice(templates)
    return " ".join(chosen_template.format(**fillings).split()) # .split() and .join() to clean up extra spaces